package com.itheima.studentservlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取请求对象中的数据;
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        String score = request.getParameter("score");
        //将获取到的数据存储在stu.txt文件中

        String realPath = this.getServletContext().getRealPath("/stu.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
        bw.write(" 姓名:"+username+" 年龄:"+age+" 成绩:"+score);
        bw.newLine();
        bw.close();
        //给客户端响应一个成功的消息
        PrintWriter writer = response.getWriter();
        writer.print("添加成功!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
